{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Dressmaker - Easy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loading spark-stubs, spark-hive\n",
      "Adding Hive conf dir /opt/hive/conf to classpath\n",
      "Creating SparkSession\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "SLF4J: No SLF4J providers were found.\n",
      "SLF4J: Defaulting to no-operation (NOP) logger implementation\n",
      "SLF4J: See https://www.slf4j.org/codes.html#noProviders for further details.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<a target=\"_blank\" href=\"http://jupyter:4040\">Spark UI</a>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "\u001b[32mimport \u001b[39m\u001b[36m$ivy.$                                  \n",
       "\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.log4j.{Level, Logger}\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark.sql._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark.sql.types._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark.sql.functions._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36morg.apache.spark.sql.expressions.Window\n",
       "\n",
       "\u001b[39m\n",
       "\u001b[36mspark\u001b[39m: \u001b[32mSparkSession\u001b[39m = org.apache.spark.sql.SparkSession@4b52afa9"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import $ivy.`org.apache.spark::spark-sql:3.4.0`\n",
    "\n",
    "import org.apache.log4j.{Level, Logger}\n",
    "Logger.getLogger(\"org\").setLevel(Level.OFF)\n",
    "\n",
    "import org.apache.spark._\n",
    "import org.apache.spark.sql._\n",
    "import org.apache.spark.sql.types._\n",
    "import org.apache.spark.sql.functions._\n",
    "import org.apache.spark.sql.expressions.Window\n",
    "\n",
    "val spark = {\n",
    "    NotebookSparkSession.builder()\n",
    "    .progress(false)\n",
    "    .appName(\"app17-1\")\n",
    "    // .master(\"spark://192.168.31.31:7077\")\n",
    "    .master(\"local[*]\")\n",
    "    .config(\"spark.sql.warehouse.dir\", \n",
    "            \"hdfs://192.168.31.31:9000/user/hive/warehouse\") \n",
    "    .config(\"spark.cores.max\", \"4\") \n",
    "    .config(\"spark.executor.instances\", \"1\") \n",
    "    .config(\"spark.executor.cores\", \"2\") \n",
    "    .config(\"spark.executor.memory\", \"10g\") \n",
    "    .config(\"spark.shuffle.service.enabled\", \"false\") \n",
    "    .config(\"spark.dynamicAllocation.enabled\", \"false\") \n",
    "    .config(\"spark.sql.catalogImplementation\", \"hive\")\n",
    "    .config(\"spark.sql.repl.eagerEval.enabled\", \"true\")\n",
    "    .config(\"spark.driver.allowMultipleContexts\", \"true\")\n",
    "    .getOrCreate()\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\u001b[32mimport \u001b[39m\u001b[36mspark.implicits._\n",
       "\u001b[39m\n",
       "\u001b[32mimport \u001b[39m\u001b[36mspark.sqlContext.implicits._\n",
       "\u001b[39m\n",
       "defined \u001b[32mfunction\u001b[39m \u001b[36msc\u001b[39m\n",
       "\u001b[36mhiveCxt\u001b[39m: \u001b[32msql\u001b[39m.\u001b[32mhive\u001b[39m.\u001b[32mHiveContext\u001b[39m = org.apache.spark.sql.hive.HiveContext@b3993c9"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import spark.implicits._\n",
    "import spark.sqlContext.implicits._\n",
    "def sc = spark.sparkContext\n",
    "val hiveCxt = new org.apache.spark.sql.hive.HiveContext(sc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "defined \u001b[32mclass\u001b[39m \u001b[36mRichDF\u001b[39m"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "// Credit to Aivean\n",
    "implicit class RichDF(val ds:DataFrame) {\n",
    "    def showHTML(limit: Int = 50, truncate: Int = 100) = {\n",
    "        import xml.Utility.escape\n",
    "        val data = ds.take(limit)\n",
    "        val header = ds.schema.fieldNames.toSeq        \n",
    "        val rows: Seq[Seq[String]] = data.map { row =>\n",
    "          row.toSeq.map {cell =>\n",
    "            val str = cell match {\n",
    "              case null => \"null\"\n",
    "              case binary: Array[Byte] => binary.map(\"%02X\".format(_)).mkString(\"[\", \" \", \"]\")\n",
    "              case array: Array[_] => array.mkString(\"[\", \", \", \"]\")\n",
    "              case seq: Seq[_] => seq.mkString(\"[\", \", \", \"]\")\n",
    "              case _ => cell.toString\n",
    "            }\n",
    "            if (truncate > 0 && str.length > truncate) {\n",
    "              // do not show ellipses for strings shorter than 4 characters.\n",
    "              if (truncate < 4) str.substring(0, truncate)\n",
    "              else str.substring(0, truncate - 3) + \"...\"\n",
    "            } else {\n",
    "              str\n",
    "            }\n",
    "          }: Seq[String]\n",
    "        }\n",
    "    publish.html(s\"\"\" <table>\n",
    "                <tr>\n",
    "                 ${header.map(h => s\"<th>${escape(h)}</th>\").mkString}\n",
    "                </tr>\n",
    "                ${rows.map {row =>\n",
    "                  s\"<tr>${row.map{c => s\"<td>${escape(c)}</td>\" }.mkString}</tr>\"\n",
    "                }.mkString}\n",
    "            </table>\n",
    "        \"\"\")\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\u001b[36mjmcust\u001b[39m: \u001b[32mDataFrame\u001b[39m = [c_no: int, c_name: string ... 2 more fields]\n",
       "\u001b[36mdressmaker\u001b[39m: \u001b[32mDataFrame\u001b[39m = [d_no: int, d_name: string ... 2 more fields]\n",
       "\u001b[36mdress_order\u001b[39m: \u001b[32mDataFrame\u001b[39m = [order_no: int, cust_no: int ... 2 more fields]\n",
       "\u001b[36mconstruction\u001b[39m: \u001b[32mDataFrame\u001b[39m = [maker: int, order_ref: int ... 3 more fields]\n",
       "\u001b[36mquantities\u001b[39m: \u001b[32mDataFrame\u001b[39m = [style_q: int, size_q: int ... 1 more field]\n",
       "\u001b[36morder_line\u001b[39m: \u001b[32mDataFrame\u001b[39m = [order_ref: int, line_no: int ... 3 more fields]\n",
       "\u001b[36mgarment\u001b[39m: \u001b[32mDataFrame\u001b[39m = [style_no: int, description: string ... 2 more fields]\n",
       "\u001b[36mmaterial\u001b[39m: \u001b[32mDataFrame\u001b[39m = [material_no: int, fabric: string ... 3 more fields]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "val jmcust = hiveCxt.table(\"sqlzoo.jmcust\")\n",
    "val dressmaker = hiveCxt.table(\"sqlzoo.dressmaker\")\n",
    "val dress_order = hiveCxt.table(\"sqlzoo.dress_order\")\n",
    "val construction = hiveCxt.table(\"sqlzoo.construction\")\n",
    "val quantities = hiveCxt.table(\"sqlzoo.quantities\")\n",
    "val order_line = hiveCxt.table(\"sqlzoo.order_line\")\n",
    "val garment = hiveCxt.table(\"sqlzoo.garment\")\n",
    "val material = hiveCxt.table(\"sqlzoo.material\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.\n",
    "List the post code, order number, order date and garment descriptions for all items associated with Ms Brown."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>post_code</th><th>order_no</th><th>order_date</th><th>description</th>\n",
       "                </tr>\n",
       "                <tr><td>B2 5AB   </td><td>9</td><td>2002-02-27</td><td>Shorts              </td></tr><tr><td>B2 5AB   </td><td>7</td><td>2002-02-21</td><td>Suntop              </td></tr><tr><td>B2 5AB   </td><td>7</td><td>2002-02-21</td><td>Sundress            </td></tr><tr><td>B2 5AB   </td><td>7</td><td>2002-02-21</td><td>Short Skirt         </td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "\u001b[36mt1\u001b[39m: \u001b[32mDataFrame\u001b[39m = [post_code: string, order_no: int ... 2 more fields]\n",
       "\u001b[36mt2\u001b[39m: \u001b[32mDataFrame\u001b[39m = [post_code: string, order_no: int ... 2 more fields]"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "val t1 = (jmcust.filter(trim(jmcust(\"c_name\")) === \"Ms Brown\")\n",
    "      .join(dress_order, (jmcust(\"c_no\") === dress_order(\"cust_no\")))\n",
    "      .join(order_line, (dress_order(\"order_no\") === order_line(\"order_ref\")))\n",
    "      .join(garment, (order_line(\"ol_style\") === garment(\"style_no\")))\n",
    "      .withColumnRenamed(\"c_post_code\", \"post_code\")\n",
    "      .select(\"post_code\", \"order_no\", \"order_date\", \"description\"))\n",
    "val t2 = (dressmaker.filter(trim(dressmaker(\"d_name\")) === \"Ms Brown\")\n",
    "      .join(construction, (dressmaker(\"d_no\") === construction(\"maker\")))\n",
    "      .join(dress_order, (construction(\"order_ref\") === dress_order(\"order_no\")))\n",
    "      .join(order_line, (dress_order(\"order_no\") === order_line(\"order_ref\")))\n",
    "      .join(garment, (order_line(\"ol_style\") === garment(\"style_no\")))\n",
    "      .withColumnRenamed(\"d_post_code\", \"post_code\")\n",
    "      .select(\"post_code\", \"order_no\", \"order_date\", \"description\"))\n",
    "t1.union(t2).showHTML()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.\n",
    "List the customer name, postal information, order date and order number of all orders that have been completed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>c_name</th><th>c_post_code</th><th>order_date</th><th>order_no</th>\n",
       "                </tr>\n",
       "                <tr><td>Ms White            </td><td>E24 8PQ  </td><td>2002-02-03</td><td>5</td></tr><tr><td>Ms White            </td><td>E24 8PQ  </td><td>2002-02-03</td><td>5</td></tr><tr><td>Ms White            </td><td>E24 8PQ  </td><td>2002-02-03</td><td>5</td></tr><tr><td>Mr Brass            </td><td>FG24 9NM </td><td>2002-02-02</td><td>4</td></tr><tr><td>Mr Brass            </td><td>FG24 9NM </td><td>2002-02-02</td><td>4</td></tr><tr><td>Ms Muir             </td><td>H2 7CV   </td><td>2002-01-20</td><td>3</td></tr><tr><td>Dr Green            </td><td>SJ4 4WE  </td><td>2002-01-11</td><td>2</td></tr><tr><td>Dr Green            </td><td>SJ4 4WE  </td><td>2002-01-11</td><td>2</td></tr><tr><td>Dr Green            </td><td>SJ4 4WE  </td><td>2002-01-11</td><td>2</td></tr><tr><td>Mrs Peacock         </td><td>DD6 9NM  </td><td>2002-01-10</td><td>1</td></tr><tr><td>Mrs Peacock         </td><td>DD6 9NM  </td><td>2002-01-10</td><td>1</td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(jmcust.join(dress_order.filter(dress_order(\"completed\") === \"Y\"),\n",
    "             (jmcust(\"c_no\") === dress_order(\"cust_no\")))\n",
    " .join(order_line, (dress_order(\"order_no\") === order_line(\"order_ref\")))\n",
    " .select(\"c_name\", \"c_post_code\", \"order_date\", \"order_no\")\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3.\n",
    "Which garments have been made or are being made from \"red abstract\" or \"blue abstract\" coloured materials."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>style_no</th><th>description</th><th>colour</th>\n",
       "                </tr>\n",
       "                <tr><td>1</td><td>Trousers            </td><td>Red Abstract        </td></tr><tr><td>2</td><td>Long Skirt          </td><td>Blue Abstract       </td></tr><tr><td>2</td><td>Long Skirt          </td><td>Red Abstract        </td></tr><tr><td>4</td><td>Short Skirt         </td><td>Blue Abstract       </td></tr><tr><td>5</td><td>Sundress            </td><td>Red Abstract        </td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(garment.join(order_line, (garment(\"style_no\") === order_line(\"ol_style\")))\n",
    " .join(material.filter(lower(trim(material(\"colour\"))).isin(\n",
    "     List(\"red abstract\", \"blue abstract\"): _*)),\n",
    "     (order_line(\"ol_material\") === material(\"material_no\")))\n",
    " .select(\"style_no\", \"description\", \"colour\")\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4.\n",
    "How many garments has each dressmaker constructed? You should give the number of garments and the name and postal information of each dressmaker."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>d_no</th><th>d_name</th><th>d_post_code</th><th>cnt</th>\n",
       "                </tr>\n",
       "                <tr><td>3</td><td>Mr Needles          </td><td>E12 6LG </td><td>12</td></tr><tr><td>1</td><td>Mrs Hem             </td><td>A12 6BC </td><td>14</td></tr><tr><td>4</td><td>Ms Sew              </td><td>EF7 9KL </td><td>12</td></tr><tr><td>5</td><td>Mr Seam             </td><td>H45 7YH </td><td>12</td></tr><tr><td>6</td><td>Mr Taylor           </td><td>SH6 9RT </td><td>7</td></tr><tr><td>7</td><td>Miss Pins           </td><td>B4 9BL  </td><td>11</td></tr><tr><td>2</td><td>Miss Stitch         </td><td>DF4 7HJ </td><td>20</td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(dressmaker.join(construction, (dressmaker(\"d_no\") === construction(\"maker\")))\n",
    " .join(dress_order, (construction(\"order_ref\") === dress_order(\"order_no\")))\n",
    " .join(order_line, (dress_order(\"order_no\") === order_line(\"order_ref\")))\n",
    " .join(garment, (order_line(\"ol_style\") === garment(\"style_no\")))\n",
    " .groupBy(\"d_no\", \"d_name\", \"d_post_code\")\n",
    " .agg(count(\"line_no\").alias(\"cnt\"))\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5.\n",
    "Give the names of those dressmakers who have finished items made from silk for completed orders."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       " <table>\n",
       "                <tr>\n",
       "                 <th>d_name</th>\n",
       "                </tr>\n",
       "                <tr><td>Ms Sew              </td></tr><tr><td>Miss Stitch         </td></tr><tr><td>Mrs Hem             </td></tr><tr><td>Miss Pins           </td></tr><tr><td>Mr Needles          </td></tr>\n",
       "            </table>\n",
       "        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "(dressmaker.join(construction, (dressmaker(\"d_no\") === construction(\"maker\")))\n",
    " .join(dress_order.filter(dress_order(\"completed\") === \"Y\"), \n",
    "       (construction(\"order_ref\") === dress_order(\"order_no\")))\n",
    " .join(order_line, (dress_order(\"order_no\") === order_line(\"order_ref\")))\n",
    " .join(garment, (order_line(\"ol_style\") === garment(\"style_no\")))\n",
    " .join(material.filter(lower(trim(material(\"fabric\"))) === \"silk\"), \n",
    "        (order_line(\"ol_material\") === material(\"material_no\")))\n",
    " .select(\"d_name\")\n",
    " .distinct()\n",
    " .showHTML())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "spark.stop()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Scala",
   "language": "scala",
   "name": "scala"
  },
  "language_info": {
   "codemirror_mode": "text/x-scala",
   "file_extension": ".sc",
   "mimetype": "text/x-scala",
   "name": "scala",
   "nbconvert_exporter": "script",
   "version": "2.12.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
